package com.qunar.dyds.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;

import com.sun.imageio.plugins.bmp.BMPImageReader;
import com.sun.imageio.plugins.gif.GIFImageReader;
import com.sun.imageio.plugins.jpeg.JPEGImageReader;
import com.sun.imageio.plugins.png.PNGImageReader;

public class ImageUtil {

    /**
     * 读取文件流类型
     * 
     * @param path 文件路径
     * @return 如果不是图片类型则为空，否侧返回图片类型
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
    public static String getImageType(InputStream in) throws IOException {
        int leng = in.available();
        BufferedInputStream buff = new BufferedInputStream(in);
        byte[] mapObj = new byte[leng];
        buff.read(mapObj, 0, leng);
        String type = "";
        ByteArrayInputStream bais = null;
        MemoryCacheImageInputStream mcis = null;
        try {
            bais = new ByteArrayInputStream(mapObj);
            mcis = new MemoryCacheImageInputStream(bais);
            Iterator itr = ImageIO.getImageReaders(mcis);
            while (itr.hasNext()) {
                ImageReader reader = (ImageReader) itr.next();
                if (reader instanceof GIFImageReader) {
                    type = "gif";
                } else if (reader instanceof JPEGImageReader) {
                    type = "jpg";
                } else if (reader instanceof PNGImageReader) {
                    type = "png";
                } else if (reader instanceof BMPImageReader) {
                    type = "bmp";
                }
            }
        } finally {
            if (bais != null) {
                try {
                    bais.close();
                } catch (IOException ioe) {

                }
            }

            if (mcis != null) {
                try {
                    mcis.close();
                } catch (IOException ioe) {

                }
            }
        }
        return type;
    }
}
